<?php

namespace app\supplier\controller;

use think\Controller;
use function GuzzleHttp\json_decode;
use function GuzzleHttp\json_encode;
use app\erp\model\Orderdb;

class Hetong extends Controller {
	protected $uri = 'https://api.letsign.com';
	protected $version = 'v1';
	protected $appCode = 'E7046224633359500035';
	protected $appSecret = 'eAxg2Q^yQ4W9*r7q!$^0R^^53q!9^$2xMfThP6Y1#V2v2S#8*$Ber8Zseg$3&1sn';
	protected $base_url = 'https://tailongji.dixintong.com/';
	protected $HEADER = [ 
			"Content-Type:application/json" 
	];
	protected $param = array ();
	protected $base_param = array ();
	protected $url = '';
	protected $action_uri = '';
	protected $pdf_url = '';
	public $request;
	protected $signerCode = 'ent_8257eaeef01d4748931291eb523e1111'; // 执行enterprise函数获得，手动执行，执行时需要将方法设置为public 每次执行都需要修改这个值
	public function _initialize() {
		header ( "Access-Control-Allow-Origin: *" );
		header ( 'Content-Type:application/json; charset=utf-8' );
		
		set_time_limit ( 0 );
		ini_set ( 'memory_limit', '256M' );
		$this->param = array (
				"appCode" => $this->appCode,
				"version" => $this->version,
				"timestamp" => $this->msectime () 
		);
		$this->base_param = $this->param;
		$this->pdf_url = '';
	}
	protected function msectime() {
		list ( $msec, $sec ) = explode ( ' ', microtime () );
		$mictime = sprintf ( '%.0f', (floatval ( $msec ) + floatval ( $sec )) * 1000 );
		return $mictime;
	}
	protected function makeSign() {
		ksort ( $this->param );
		$string = $this->toUrlParams ();
		$string = $string . $this->appSecret;
		$result = sha1 ( $string );
		return $result;
	}
	protected function toUrlParams() {
		$buff = "";
		foreach ( $this->param as $k => $v ) {
			if ($k != "sign" && $v != "" && ! is_array ( $v )) {
				$buff .= $k . "=" . $v;
			}
		}
		$buff .= $this->action_uri;
		return md5 ( $buff );
	}
	protected function doCurl() {
		if ($this->HEADER [0] == 'Content-Type:application/json') {
			$param = json_encode ( $this->param );
		} else {
			$param = $this->param;
		}
		
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $this->url );
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $param );
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, $this->HEADER );
		$output = curl_exec ( $ch );
		curl_close ( $ch );
		$temp = json_decode ( $output, true );
		return $temp;
	}
	protected function buildParam() {
		$token = $this->makeSign ();
		$this->param ["token"] = $token;
		if ($this->pdf_url) {
			$f = curl_file_create ( $this->pdf_url );
			$this->param ['contractFile'] = $f;
		}
		// print_r($this->param);
		return $this->doCurl ();
	}
	// 打包
	public function zipDown($out_order_no) {
		$zip_name = 'uploads/Excel/hetong/' . $out_order_no . '.zip';
		$zip = new \ZipArchive ();
		$res = $zip->open ( $zip_name, \ZipArchive::CREATE );
		if ($res === true) {
			$orderdb = new Orderdb ();
			$get_order = $orderdb->useGlobalScope ( false )->where ( 'out_order_no', $out_order_no )->find ();
			if ($get_order) {
				$get_order = $get_order->toArray ();
				if ($get_order ['cght']) {
					$zip->addFile ( str_replace ( $this->base_url, '', $get_order ['cght'] ) );
				}
				if ($get_order ['shd']) {
					$zip->addFile ( str_replace ( $this->base_url, '', $get_order ['shd'] ) );
				}
				if ($get_order ['ysd']) {
					$zip->addFile ( str_replace ( $this->base_url, '', $get_order ['ysd'] ) );
				}
				if ($get_order ['xsht']) {
					$zip->addFile ( str_replace ( $this->base_url, '', $get_order ['xsht'] ) );
				}
			}
		} else {
			print_r ( '创建失败' );
		}
		$zip->close ();
		header ( "Content-Type: application/zip" );
		header ( "Content-Transfer-Encoding: Binary" );
		header ( "Content-Length: " . filesize ( $zip_name ) );
		header ( "Content-Disposition: attachment; filename=\"" . basename ( $zip_name ) . "\"" );
		readfile ( $zip_name );
		@unlink ( $zip_name );
	}
	// 上传合同
	public function uploadOpt($out_order_no, $type,$all_page) {
		$name_ext = '';
		switch ($type) {
			case 'callet' :
				$name_ext = '采购合同.pdf';
				break;
			case 'post' :
				$name_ext = '送货验收单.pdf';
				break;
			case 'ysd' :
			    $name_ext = '验收单.pdf';
			    break;
			case 'sale' :
				$name_ext = '销售合同.pdf';
				break;
		}
		$this->pdf_url = $_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/' . $type . '/' . $out_order_no . $name_ext;
		
		$this->url = $this->uri . '/open-api-lite/contract/file';
		$this->action_uri = '/open-api-lite/contract/file';
		$this->HEADER = [ 
				"Content-Type:multipart/form-data" 
		];
		$output = $this->buildParam ();
		// print_r($output);
		$contractCode = $output ['data'] ['contractCode'];
		$orderdb = new Orderdb ();
		switch ($type) {
			case 'callet' :
				$save_data ['cght_code'] = $contractCode;
				break;
			case 'post' :
				$save_data ['shd_code'] = $contractCode;
				break;
			case 'ysd' :
			    $save_data ['ysd_code'] = $contractCode;
			    break;
			case 'sale' :
				$save_data ['xsht_code'] = $contractCode;
				break;
		}
		$orderdb->useGlobalScope ( false )->where ( 'out_order_no', $out_order_no )->update ( $save_data );
		$this->autoSign ( $contractCode, $out_order_no, $type ,$all_page);
		//print_r ( $output );
		return 'success';
		// print_r ( $output );
	}
	public function autoSign($contractCode, $out_order_no, $type, $all_page) {
		$this->url = $this->uri . '/open-api-lite/contract/sign/auto';
		$this->action_uri = '/open-api-lite/contract/sign/auto';
		$this->HEADER = [ 
				"Content-Type:application/json" 
		];
		$this->pdf_url = '';
		$this->param = $this->base_param;
		$this->param ['signerCode'] = $this->signerCode;
		$this->param ['contractCode'] = $contractCode;
		$this->param ['autoSignAuthorization'] = '1';
		$this->param ['transactionCode'] = $type . '_' . $out_order_no . '_' . time () . rand ( 100, 999 );
		// print_r ( $this );
		switch ($type) {
			case 'sale' :
				// 销售合同
				// $this->param['scanPage'] = '1,2,3';// 扫描位置
				// $this->param['keyWord'] = '盖章处关键字';
				
				// $this->param ['keyWord'] = '北京市泰龙吉贸易有限公司';
				$this->param ['signCrossPage'] = 2; // 骑缝章 2是需要
				$signCoordinate = array ();
				for($i = 0; $i < $all_page; $i ++) {
					$temp ['pdfPage'] = $i + 1; // 第1页
					$temp ['vertical'] = 350; // 纵坐标
					$temp ['horizontal'] = 600; // 横坐标
					array_push ( $signCoordinate, $temp );
				}
				$this->param ['signCoordinate'] = json_encode ( $signCoordinate );
				break;
				
			case 'post' :
				// 送货单
				 //$this->param['scanPage'] = '1,2,3';// 扫描位置
				// $this->param['keyWord'] = '盖章处关键字';
				$this->param ['signCrossPage'] = 1; // 骑缝章 2是需要
				 $this->param ['keyWord'] = '泰龙吉贸易';
				break;
				
			case 'ysd' :
			   // 送货单
			   //$this->param['scanPage'] = '1,2,3';// 扫描位置
			   // $this->param['keyWord'] = '盖章处关键字';
			   $this->param ['signCrossPage'] = 1; // 骑缝章 2是需要
			   $this->param ['keyWord'] = '泰龙吉贸易';
			   break;	
			   
			case 'callet' :
				// 采购合同
				// $this->param['scanPage'] = '1,2,3';// 扫描位置
				// $this->param['keyWord'] = '盖章处关键字';
			//	$this->param ['keyWord'] = '北京市泰龙吉贸易有限公司';
				$this->param ['signCrossPage'] = 1; // 骑缝章 2是需要
				$signCoordinate = array ();
				for($i = 0; $i < $all_page; $i ++) {
					$temp ['pdfPage'] = $i + 1; // 第1页
					$temp ['vertical'] = 670; // 纵坐标
					$temp ['horizontal'] = 180; // 横坐标
					array_push ( $signCoordinate, $temp );
				}
				$this->param ['signCoordinate'] = json_encode ( $signCoordinate );
				break;
		}
		if($type == 'ysd'){
            $this->param ['postSignCallback'] = 'https://tailongji.dixintong.com' . url ( 'supplier/hetong/notiryUrl' );
        } else {
            $this->param ['postSignCallback'] = 'https://tailongji.dixintong.com' . url ( 'hetong/notiryUrl' );
        }
		$this->param ['postSignCallback'] = 'https://tailongji.dixintong.com' . url ( 'supplier/hetong/notiryUrl' );
		//print_r ( $this->param );
		$result = $this->buildParam ();
		/*print_r('自动签名:');
		print_r ( $result );*/
	}
	// 下载合同
	public function download($contractCode) {
		$this->url = $this->uri . '/open-api-lite/contract/file/download';
		$this->action_uri = '/open-api-lite/contract/file/download';
		$this->param ['contractCode'] = $contractCode;
		$result = $this->buildParam ();
		return $result ['data'] ['downloadUrl'];
	}
	// 生成企业签署人
	public function enterprise() {
		$this->url = $this->uri . '/open-api-lite/signer/enterprise';
		$this->action_uri = '/open-api-lite/signer/enterprise';
		$this->HEADER = [ 
				"Content-Type:multipart/form-data" 
		];
		$this->param ['entQualificationType'] = '1';
		$this->param ['entName'] = '北京市泰龙吉贸易有限公司';
		$this->param ['entQualificationNum'] = '91110105675715354X';
		$this->param ['corporateName'] = '侯庆红';
		$this->param ['personIdType'] = '0';
		$this->param ['personName'] = '罗继东';
		$this->param ['personIdCard'] = '152502197611100710';
		$this->param ['roleType'] = '2';
		$output = $this->buildParam ();
		print_r ( $output );
	}
	public function ajaxReturn($data, $json_option = 0) {
		header ( 'Content-Type:application/json; charset=utf-8' );
		exit ( json_encode ( $data, $json_option ) );
	}
	public function index() {
		echo 'hi';
	}
	public function notiryUrl() {
		define ( 'SITE_ID', 117 );
		define ( 'PARTNER_ID', 25 );
		define ( 'MEMBER_ID', 1 );
		$request = request ();
		$this->request = $request->param ();
		if (isset ( $this->request ['resultCode'] ) && $this->request ['resultCode'] == 1) {
			$temp = explode ( '_', $this->request ['transactionCode'] );
			$out_order_no = $temp [1];
			$file_pre = '送货单';
			switch ($temp [0]) {
				case 'callet' :
					$file_pre = '采购合同';
					break;
				case 'post' :
					$file_pre = '送货验收单';
					break;
				case 'ysd' :
				    $file_pre = '验收单';
				    break;
				case 'sale' :
					$file_pre = '销售合同';
					break;
			}
			$orderdb = new Orderdb ();
			$file_path = $this->downPdf ( $this->request ['downloadUrl'], $file_pre, $out_order_no );
			switch ($temp [0]) {
				case 'callet' :
					$save_data ['cght'] = $file_path;
					break;
				case 'post' :
					$save_data ['shd'] = $file_path;
					break;
				case 'ysd' :
				    $save_data ['ysd'] = $file_path;
				    break;
				case 'sale' :
					$save_data ['xsht'] = $file_path;
					break;
			}
			$orderdb->useGlobalScope ( false )->where ( 'out_order_no', $out_order_no )->update ( $save_data );
			$return ['code'] = 0;
			$return ['description'] = "success";
			$this->ajaxReturn ( $return );
		}
		// file_put_contents('hetong_'.date('H:i:s').'.txt', $this->request);
	}
	public function downPdf($file, $file_pre, $out_order_no) {
		$file = file_get_contents ( $file );
		$time = time ();
		$pic_local_path = $_SERVER ['DOCUMENT_ROOT'] . '/uploads/Excel/hetong/';
		$pic_local = $pic_local_path . $out_order_no . $file_pre . '.pdf';
		if (! file_exists ( $pic_local_path )) {
			@mkdir ( $pic_local_path, 0777 );
			@chmod ( $pic_local_path, 0777 );
		}
		file_put_contents ( $pic_local, $file );
		return $this->base_url . 'uploads/Excel/hetong/' . $out_order_no . $file_pre . '.pdf';
	}
}